package org.elephantt.webby;

import org.apache.commons.cli.*;

/**
 * HTTP server configuration. Can construct itself from a command line.
 */
public class HttpApplicationConfig {
  private final int port;
  private final int minThreads;
  private final int maxThreads;

  public HttpApplicationConfig() {
    port = 8080;
    minThreads = 10;
    maxThreads = 100;
  }

  public HttpApplicationConfig(int port, int minThreads, int maxThreads) {
    this.port = port;
    this.minThreads = minThreads;
    this.maxThreads = maxThreads;
  }

  public int getPort() {
    return port;
  }

  public int getMinThreads() {
    return minThreads;
  }

  public int getMaxThreads() {
    return maxThreads;
  }

  /**
   * Creates an instance from command line arguments.
   * @param commandLine
   * @return
   */
  public static HttpApplicationConfig create(CommandLine commandLine) {
    int port = 8080;
    int minthreads = 2;
    int maxthreads = 100;

    if (commandLine.hasOption("port")) {
      port = Integer.parseInt(commandLine.getOptionValue("port"));
    }

    if (commandLine.hasOption("minthreads")) {
      minthreads = Integer.parseInt(commandLine.getOptionValue("minthreads"));
    }

    if (commandLine.hasOption("maxthreads")) {
      maxthreads = Integer.parseInt(commandLine.getOptionValue("maxthreads"));
    }

    return new HttpApplicationConfig(port, minthreads, maxthreads);
  }

  public static HttpApplicationConfig create(String[] args) throws ParseException {
    return create((new PosixParser()).parse(new HttpApplicationOptions(), args));
  }

  /**
   * Create Options that this respects
   */
  public static class HttpApplicationOptions extends Options {
    public HttpApplicationOptions() {
      addOption(OptionBuilder.withLongOpt("port")
              .withDescription("listen port")
              .withValueSeparator('=')
              .hasArg()
              .create());

      addOption(OptionBuilder.withLongOpt("minthreads")
              .withDescription("minimum request threads")
              .withValueSeparator('=')
              .hasArg()
              .create());

      addOption(OptionBuilder.withLongOpt("maxthreads")
              .withDescription("maximum request threads")
              .withValueSeparator('=')
              .hasArg()
              .create());
    }
  }
}